package cn.lijiajia3515.cairo.auth.framework.security.web.authentication.captcha;

import lombok.Setter;
import org.springframework.core.log.LogMessage;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

public abstract class AbstractCaptchaFilter extends OncePerRequestFilter {
	/**
	 * 校验码 码 属性名称
	 */
	public static final String VERIFY_CODE_ATTRIBUTE_NAME = "verify_code";

	/**
	 * 验证 过期时间 属性名称
	 */
	public static final String VERIFY_EXPIRE_ATTRIBUTE_NAME = "verify_expire";


	/**
	 * 校验码 属性名
	 */
	@Setter
	protected String verifyCodeAttributeName = "verify_code";

	/**
	 * 校验码 过期时间
	 */
	@Setter
	protected String verifyCodeExpireAttributeName = "verify_code_expire";

	/**
	 * 匹配路径
	 */
	@Setter
	protected RequestMatcher requestMatcher;

	/**
	 * 实例
	 *
	 * @param requestMatcher 匹配路径
	 */
	public AbstractCaptchaFilter(RequestMatcher requestMatcher) {
		this.requestMatcher = requestMatcher;
	}

	/**
	 * Allow subclasses to modify when a captcha should take place.
	 *
	 * @param request  the request
	 * @param response the response
	 * @return <code>true</code> if logout should occur, <code>false</code> otherwise
	 */
	protected boolean requires(HttpServletRequest request, HttpServletResponse response) {
		if (this.requestMatcher.matches(request)) {
			return true;
		}
		if (this.logger.isTraceEnabled()) {
			this.logger.trace(LogMessage.format("Did not match request to %s", this.requestMatcher));
		}
		return false;
	}

	/**
	 * 获取 校验码 密码 属性名称
	 *
	 * @return 属性名称
	 */
	public String getVerifyCodeAttributeName() {
		return Optional.ofNullable(verifyCodeAttributeName).orElse(VERIFY_CODE_ATTRIBUTE_NAME);
	}

	/**
	 * 获取 校验码 过期时间 属性名称
	 *
	 * @return 属性名称
	 */
	public String getVerifyCodeExpireAttributeName() {
		return Optional.ofNullable(verifyCodeExpireAttributeName).orElse(VERIFY_EXPIRE_ATTRIBUTE_NAME);
	}
}
